<script setup lang="tsx">
import { NButton, NPopconfirm } from 'naive-ui';
import { useBoolean } from '@sa/hooks';
import { useAppStore } from '@/store/modules/app';
import { useAuth } from '@/hooks/business/auth';
import { useTable, useTableOperate } from '@/hooks/common/table';
import { $t } from '@/locales';
import { transDeleteParams } from '@/utils/common';
import { formatDateTime } from '@/utils/date';
import { fetchDeleteTenant, fetchGetTenantList } from '@/service/api';
import { useDict } from '@/hooks/business/dict';
import TenantOperateDrawer from './modules/tenant-operate-drawer.vue';
import ModuleAuthModal from './modules/module-auth-modal.vue';

defineOptions({
  name: 'SysTenantPage'
});

const appStore = useAppStore();

const { bool: moduleModalVisible, setTrue: openModuleModal } = useBoolean();

const { hasAuth } = useAuth();

const { dictTag } = useDict();

const { columns, columnChecks, data, loading, getData, getDataByPage, mobilePagination } = useTable({
  apiFn: fetchGetTenantList,
  apiParams: {
    page: 1,
    pageSize: 20
  },
  columns: () => [
    {
      type: 'selection',
      align: 'center',
      width: 48
    },
    {
      key: 'index',
      title: $t('common.index'),
      width: 64,
      align: 'center'
    },
    {
      key: 'name',
      title: $t('page.system.tenant.name'),
      align: 'center',
      width: 150,
      minWidth: 150
    },
    {
      key: 'code',
      title: $t('page.system.tenant.code'),
      align: 'center',
      width: 150,
      minWidth: 150
    },
    {
      key: 'description',
      title: $t('page.system.tenant.description'),
      align: 'center',
      minWidth: 150
    },
    {
      key: 'sort',
      title: $t('page.system.tenant.sort'),
      align: 'center',
      width: 150,
      minWidth: 150
    },
    {
      key: 'createUser',
      title: $t('page.system.tenant.createUser'),
      align: 'center',
      width: 150,
      minWidth: 150
    },
    {
      key: 'createTime',
      title: $t('page.system.tenant.createTime'),
      align: 'center',
      width: 180,
      minWidth: 180,
      render: row => formatDateTime(row.createTime)
    },
    {
      key: 'status',
      title: $t('page.system.tenant.status'),
      align: 'center',
      width: 150,
      minWidth: 150,
      render: row => dictTag('status', row.status)
    },
    {
      key: 'operate',
      title: $t('common.operate'),
      align: 'center',
      width: 200,
      minWidth: 200,
      render: row => (
        <div class="flex-center gap-8px">
          {hasAuth('sys:tenant:module:add') && (
            <NButton type="primary" quaternary size="small" onClick={() => handleModuleAuth(row.id)}>
              {$t('page.system.tenant.moduleAuth')}
            </NButton>
          )}
          {hasAuth('sys:tenant:update') && (
            <NButton type="primary" quaternary size="small" onClick={() => edit(row.id)}>
              {$t('common.edit')}
            </NButton>
          )}
          {hasAuth('sys:tenant:delete') && (
            <NPopconfirm onPositiveClick={() => handleDelete(row.id)}>
              {{
                default: () => $t('common.confirmDelete'),
                trigger: () => (
                  <NButton type="error" quaternary size="small">
                    {$t('common.delete')}
                  </NButton>
                )
              }}
            </NPopconfirm>
          )}
        </div>
      )
    }
  ]
});

const { drawerVisible, operateType, checkedRowKeys, editingId, editingData, handleId, handleAdd, handleEdit, onDeleted, onBatchDeleted } =
  useTableOperate(data, getData);

function edit(id: string) {
  handleEdit(id);
}

function handleModuleAuth(id: string) {
  handleId(id);
  openModuleModal();
}

async function handleDelete(id: string) {
  // request
  const { error, data: result } = await fetchDeleteTenant(transDeleteParams([id]));
  if (!error && result) {
    await onDeleted();
  }
}

async function handleBatchDelete() {
  // request
  const { error, data: result } = await fetchDeleteTenant(transDeleteParams(checkedRowKeys.value));
  if (!error && result) {
    await onBatchDeleted();
  }
}
</script>

<template>
  <div class="min-h-500px flex-col-stretch gap-8px overflow-hidden lt-sm:overflow-auto">
    <div class="custom-warning-alert">
      <NAlert size="small" :show-icon="false" type="default">
        租户的 "启用"、"禁用"、"模块权限" 操作成功后将强制退出关联的在线用户，请谨慎操作。
      </NAlert>
    </div>
    <NCard :bordered="false" class="sm:flex-1-hidden card-wrapper" content-class="flex-col">
      <TableHeaderOperation
        v-model:columns="columnChecks"
        :checked-row-keys="checkedRowKeys"
        :loading="loading"
        add-auth="sys:tenant:add"
        delete-auth="sys:tenant:delete"
        @add="handleAdd"
        @delete="handleBatchDelete"
        @refresh="getData"
      />
      <NDataTable
        v-model:checked-row-keys="checkedRowKeys"
        remote
        striped
        size="small"
        class="sm:h-full"
        :data="data"
        :scroll-x="962"
        :columns="columns"
        :flex-height="!appStore.isMobile"
        :loading="loading"
        :single-line="false"
        :row-key="row => row.id"
        :pagination="mobilePagination"
      />
      <TenantOperateDrawer v-model:visible="drawerVisible" :operate-type="operateType" :row-data="editingData" @submitted="getDataByPage" />
      <ModuleAuthModal v-model:visible="moduleModalVisible" :tenant-id="editingId" />
    </NCard>
  </div>
</template>

<style lang="scss" scoped></style>
